<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索表单 -->
      <el-col :span="24">
        <el-card class="search-card">
          <el-form :model="searchForm" ref="searchRef" :inline="true" label-width="80px">
            <el-form-item label="出发站" prop="departureStation">
              <el-input
                v-model="searchForm.departureStation"
                placeholder="请输入出发站"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="到达站" prop="arrivalStation">
              <el-input
                v-model="searchForm.arrivalStation"
                placeholder="请输入到达站"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="出行日期" prop="travelDate">
              <el-date-picker
                v-model="searchForm.travelDate"
                type="date"
                placeholder="请选择出行日期"
                value-format="YYYY-MM-DD"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索车次</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 车次列表 -->
    <el-row style="margin-top: 20px">
      <el-col :span="24">
        <el-card v-loading="trainListLoading">
          <template #header>
            <span>车次信息</span>
          </template>
          
          <el-table :data="trainList" style="width: 100%">
            <el-table-column prop="trainNumber" label="车次" width="120" />
            <el-table-column prop="trainName" label="列车名称" width="180" />
            <el-table-column prop="departureStation" label="出发站" width="120" />
            <el-table-column prop="arrivalStation" label="到达站" width="120" />
            <el-table-column label="出发时间" width="180">
              <template #default="scope">
                <span>{{ formatTime(scope.row.departureTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="到达时间" width="180">
              <template #default="scope">
                <span>{{ formatTime(scope.row.arrivalTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="primary" size="small" @click="showSeatSelection(scope.row)">
                  选座购票
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="trainList.length === 0 && !trainListLoading" style="text-align: center; padding: 50px;">
            <span style="color: #999">暂无车次信息，请搜索车次</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 选座对话框 -->
    <el-dialog v-model="seatDialogVisible" :title="`${selectedTrain.trainNumber} - 选择座位`" width="800px" append-to-body>
      <div v-loading="seatConfigLoading">
        <el-row v-for="seatConfig in seatConfigs" :key="seatConfig.seatConfigId" style="margin-bottom: 20px">
          <el-col :span="24">
            <el-card>
              <template #header>
                <div style="display: flex; justify-content: space-between; align-items: center">
                  <span>{{ seatConfig.seatClassName }}</span>
                  <span style="color: #e6a23c; font-weight: bold">￥{{ seatConfig.price }}</span>
                </div>
              </template>
              
              <div style="display: flex; justify-content: space-between; align-items: center">
                <div>
                  <p>车厢：{{ seatConfig.carriageStart }}-{{ seatConfig.carriageEnd }}车厢</p>
                  <p>余票：{{ seatConfig.availableSeats }}张</p>
                </div>
                <div>
                  <el-button
                    type="primary"
                    :disabled="seatConfig.availableSeats === 0"
                    @click="selectSeatClass(seatConfig)"
                  >
                    {{ seatConfig.availableSeats === 0 ? '已售完' : '选择' }}
                  </el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 购票信息对话框 -->
    <el-dialog v-model="bookingDialogVisible" title="填写乘客信息" width="600px" append-to-body>
      <el-form ref="bookingRef" :model="bookingForm" :rules="bookingRules" label-width="100px">
        <el-form-item label="车次信息" class="train-info">
          <div>
            <p><strong>{{ selectedTrain.trainNumber }}</strong> {{ selectedTrain.trainName }}</p>
            <p>{{ selectedTrain.departureStation }} → {{ selectedTrain.arrivalStation }}</p>
            <p>{{ formatTime(selectedTrain.departureTime) }} - {{ formatTime(selectedTrain.arrivalTime) }}</p>
            <p>座位等级：{{ selectedSeatConfig.seatClassName }} ￥{{ selectedSeatConfig.price }}</p>
          </div>
        </el-form-item>
        
        <el-form-item label="乘客姓名" prop="passengerName">
          <el-input v-model="bookingForm.passengerName" placeholder="请输入乘客姓名" />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="passengerPhone">
          <el-input v-model="bookingForm.passengerPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="出行日期" prop="travelDate">
          <el-date-picker
            v-model="bookingForm.travelDate"
            type="date"
            placeholder="请选择出行日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <div style="text-align: left; margin-bottom: 10px">
            <strong>总金额：￥{{ selectedSeatConfig.price }}</strong>
          </div>
          <el-button @click="bookingDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitBooking" :loading="bookingSubmitting">
            确认购票
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Booking">
import { ref, reactive } from 'vue'
import { searchTrains, getTrainSeatConfigs } from "@/api/boot/train"
import { addTrainorder } from "@/api/boot/trainorder"

const { proxy } = getCurrentInstance()

// 搜索表单
const searchForm = reactive({
  departureStation: '',
  arrivalStation: '',
  travelDate: ''
})

// 车次列表
const trainList = ref([])
const trainListLoading = ref(false)

// 座位选择
const seatDialogVisible = ref(false)
const seatConfigs = ref([])
const seatConfigLoading = ref(false)
const selectedTrain = ref({})

// 购票信息
const bookingDialogVisible = ref(false)
const selectedSeatConfig = ref({})
const bookingSubmitting = ref(false)

const bookingForm = reactive({
  passengerName: '',
  passengerPhone: '',
  passengerIdCard: '',
  travelDate: ''
})

const bookingRules = {
  passengerName: [
    { required: true, message: "乘客姓名不能为空", trigger: "blur" }
  ],
  passengerPhone: [
    { required: true, message: "联系电话不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  travelDate: [
    { required: true, message: "出行日期不能为空", trigger: "change" }
  ]
}

// 搜索车次
function handleSearch() {
  if (!searchForm.departureStation || !searchForm.arrivalStation || !searchForm.travelDate) {
    proxy.$modal.msgWarning('请填写完整的搜索条件')
    return
  }
  
  trainListLoading.value = true
  searchTrains(searchForm.departureStation, searchForm.arrivalStation, searchForm.travelDate)
    .then(response => {
      trainList.value = response.data || []
      trainListLoading.value = false
    })
    .catch(() => {
      trainListLoading.value = false
    })
}

// 重置搜索
function resetSearch() {
  searchForm.departureStation = ''
  searchForm.arrivalStation = ''
  searchForm.travelDate = ''
  trainList.value = []
}

// 显示座位选择
function showSeatSelection(train) {
  selectedTrain.value = train
  seatDialogVisible.value = true
  seatConfigLoading.value = true
  
  getTrainSeatConfigs(train.trainId)
    .then(response => {
      seatConfigs.value = response.data || []
      seatConfigLoading.value = false
    })
    .catch(() => {
      seatConfigLoading.value = false
    })
}

// 选择座位等级
function selectSeatClass(seatConfig) {
  selectedSeatConfig.value = seatConfig
  bookingForm.travelDate = searchForm.travelDate
  seatDialogVisible.value = false
  bookingDialogVisible.value = true
}

// 提交购票
function submitBooking() {
  proxy.$refs["bookingRef"].validate(valid => {
    if (valid) {
      bookingSubmitting.value = true
      
      const bookingData = {
        trainId: selectedTrain.value.trainId,
        seatConfigId: selectedSeatConfig.value.seatConfigId,
        passengerName: bookingForm.passengerName,
        passengerPhone: bookingForm.passengerPhone,
        passengerIdCard: bookingForm.passengerIdCard,
        seatClass: selectedSeatConfig.value.seatClass,
        orderAmount: selectedSeatConfig.value.price,
        travelDate: bookingForm.travelDate,
        orderStatus: '0' // 待支付
      }
      
      addTrainorder(bookingData)
        .then(response => {
          proxy.$modal.msgSuccess("购票成功！")
          bookingDialogVisible.value = false
          resetBookingForm()
          bookingSubmitting.value = false
        })
        .catch(() => {
          bookingSubmitting.value = false
        })
    }
  })
}

// 重置购票表单
function resetBookingForm() {
  bookingForm.passengerName = ''
  bookingForm.passengerPhone = ''
  bookingForm.passengerIdCard = ''
  bookingForm.travelDate = ''
}

// 格式化时间
function formatTime(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.train-info p {
  margin: 5px 0;
  color: #606266;
}

.train-info strong {
  color: #303133;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>